package com.vancouver.knows.ui.activity.search;


import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ViewAnimator;

import com.pangu.service.ActionException;
import com.pangu.task.IResultReceiver;
import com.pangu.task.mark.ATaskMark;
import com.vancouver.knows.R;
import com.vancouver.knows.business.BSharedPrefManager;
import com.vancouver.knows.business.BusinessModule;
import com.vancouver.knows.business.bean.SearchResultInfo;
import com.vancouver.knows.business.service.impl.SearchInfoHandle;
import com.vancouver.knows.business.task.mark.SearchKeyWordTaskMark;
import com.vancouver.knows.ui.activity.TutorialActivity;
import com.vancouver.knows.ui.base.BaseActivity;
import com.vancouver.knows.util.PhoConstants;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import butterknife.OnEditorAction;
import butterknife.OnTextChanged;

/**
 * Created by Chris Li on 2016-07-11.
 */
public class NewSearchActivity extends BaseActivity implements IResultReceiver, SearchListViewAdapter.OnSearchItemClickListener {

    private static final int SEARCH_HOME_VIEW = 0;
    private static final int SEARCH_RESULTS_VIEW = 1;
    private static final int SEARCH_LOADING_VIEW = 2;

    @Bind(R.id.search_input)
    AppCompatEditText mSearchInput;
    @Bind(R.id.view_animator)
    ViewAnimator mViewAnimator;
    @Bind(R.id.trending_tags)
    RecyclerView mTrendingTags;
    @Bind(R.id.search_history)
    RecyclerView mSearchHistory;
    @Bind(R.id.post_search_result)
    View mPostSearchResult;
    @Bind(R.id.business_search_result)
    View mBusinessSearchResult;
    @Bind(R.id.event_search_result)
    View mEventSearchResult;
    @Bind(R.id.userpost_search_result)
    View mUserpostSearchResult;

    private SearchListViewAdapter mTrendingTagsAdapter;
    private SearchListViewAdapter mSearchHistoryAdapter;

    private boolean mIsFirstRun = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_search);

        setViews();
        retrieveData();
    }

    private void setViews() {
        mTrendingTags.setHasFixedSize(true);
        StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.HORIZONTAL);
        mTrendingTags.setLayoutManager(staggeredGridLayoutManager);
        mTrendingTags.setNestedScrollingEnabled(false);
        mTrendingTagsAdapter = new SearchListViewAdapter(SearchListViewAdapter.TAG_TYPE, new ArrayList<String>());
        mTrendingTagsAdapter.setOnSearchItemClickListener(this);
        mTrendingTags.setAdapter(mTrendingTagsAdapter);

        mSearchHistory.setHasFixedSize(true);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        mSearchHistory.setLayoutManager(linearLayoutManager);
        mSearchHistory.setNestedScrollingEnabled(false);
        mSearchHistoryAdapter = new SearchListViewAdapter(SearchListViewAdapter.HISTORY_TYPE, new ArrayList<String>());
        mSearchHistoryAdapter.setOnSearchItemClickListener(this);
        mSearchHistory.setAdapter(mSearchHistoryAdapter);

        ((ImageView) mPostSearchResult.findViewById(R.id.icon)).setImageResource(R.drawable.news);
        ((ImageView) mBusinessSearchResult.findViewById(R.id.icon)).setImageResource(R.drawable.shop);
        ((ImageView) mEventSearchResult.findViewById(R.id.icon)).setImageResource(R.drawable.event);
        ((ImageView) mUserpostSearchResult.findViewById(R.id.icon)).setImageResource(R.drawable.price);
    }

    /**
     * Initialize view with the data retrieved from network for trending keywords
     * and from cache for user search history.
     */
    private void retrieveData() {

        mViewAnimator.setDisplayedChild(SEARCH_LOADING_VIEW);

        BusinessModule businessModule = imContext.getBusinessModule();
        businessModule.getCacheManager().setSearchKeyWorkInfoMap(null);
        SearchKeyWordTaskMark taskMark = businessModule.getTaskMarkPool().createSearchKeyWordTaskMarkList();
        businessModule.getServiceWrapper().userSearch(this, taskMark, "", null, null, null, null); // send empty string to get list of hot keywords

        mSearchHistoryAdapter.addItems(imContext.getSharedPrefManager().getSearchHistory());
    }

    @OnClick(R.id.cancel_search)
    public void onSearchCancel() {
        if (mViewAnimator.getDisplayedChild() == SEARCH_HOME_VIEW) {
            if (mSearchInput.getText().toString().trim().isEmpty()) {
                onBackPressed();
            } else {
                mSearchInput.setText("");
            }
        } else if (mViewAnimator.getDisplayedChild() == SEARCH_RESULTS_VIEW) {
            mSearchInput.setText("");
            mViewAnimator.setDisplayedChild(SEARCH_HOME_VIEW);
        }
    }

    @OnClick(R.id.refresh_button)
    public void onRefreshKeywords() {
        mTrendingTagsAdapter.reorderItems();
    }

    @OnClick(R.id.clear_history_button)
    public void onClearHistory() {
        imContext.getSharedPrefManager().clearSearchHistory();
        mSearchHistoryAdapter.clearItems();
    }

    @OnClick({R.id.post_search_result, R.id.business_search_result, R.id.event_search_result, R.id.userpost_search_result})
    public void onSearchResultItemClicked(View view) {

        String searchTerm = mSearchInput.getText().toString().trim();
        if (searchTerm.isEmpty()) {
            return;
        }

        Intent searchResultIntent = new Intent(NewSearchActivity.this, SearchResultActivity.class);
        searchResultIntent.putExtra("SEARCH_KEYWORD", searchTerm);

        switch (view.getId()) {
            case R.id.post_search_result:
                searchResultIntent.putExtra("SEARCH_TYPE", "post");
                searchResultIntent.putExtra("TOTAL_SEARCH_RESULT", String.valueOf(mPostSearchResult.getTag()));
                break;
            case R.id.business_search_result:
                searchResultIntent.putExtra("SEARCH_TYPE", "business");
                searchResultIntent.putExtra("TOTAL_SEARCH_RESULT", String.valueOf(mBusinessSearchResult.getTag()));
                break;
            case R.id.event_search_result:
                searchResultIntent.putExtra("SEARCH_TYPE", "event");
                searchResultIntent.putExtra("TOTAL_SEARCH_RESULT", String.valueOf(mEventSearchResult.getTag()));
                break;
            case R.id.userpost_search_result:
                searchResultIntent.putExtra("SEARCH_TYPE", "userpost");
                searchResultIntent.putExtra("TOTAL_SEARCH_RESULT", String.valueOf(mUserpostSearchResult.getTag()));
                break;
        }

        imContext.getSharedPrefManager().saveSearchTerm(searchTerm);
        mSearchHistoryAdapter.addItem(searchTerm);
        startActivity(searchResultIntent);
    }

    @OnEditorAction(R.id.search_input)
    public boolean onSearchEntered(int actionId) {

        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            String searchTerm = mSearchInput.getText().toString().trim();
            if (!searchTerm.isEmpty()) {
                Message message = Message.obtain();
                message.what = PhoConstants.ACTION_USER_SEARCH;
                message.obj = searchTerm;
                sendDelayMessage(message, 100);

                imContext.getSharedPrefManager().saveSearchTerm(searchTerm);
                mSearchHistoryAdapter.addItem(searchTerm);
            }

            return true;
        }

        return false;
    }

    @OnTextChanged(value = R.id.search_input, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
    public void onTextChanged(CharSequence s) {
        if (!s.toString().isEmpty()) {
            Message message = Message.obtain();
            message.what = PhoConstants.ACTION_USER_SEARCH;
            message.obj = s.toString();
            sendDelayMessage(message, 100);
        }
    }

    @Override
    public void onSearchItemClick(String searchTerm) {

        mSearchInput.setText(searchTerm);

        Message message = Message.obtain();
        message.what = PhoConstants.ACTION_USER_SEARCH;
        message.obj = searchTerm;
        sendDelayMessage(message, 0);
    }

    @Override
    public void subHandleMessage(Message msg) {
        super.subHandleMessage(msg);

        switch (msg.what) {
            case PhoConstants.ACTION_USER_SEARCH:
                BusinessModule businessModule = imContext.getBusinessModule();
                businessModule.getCacheManager().setSearchKeyWorkInfoMap(null);
                SearchKeyWordTaskMark taskMark = businessModule.getTaskMarkPool().createSearchKeyWordTaskMarkList();
                businessModule.getServiceWrapper().userSearch(this, taskMark, (String) msg.obj, null, null, null, null);
                mViewAnimator.setDisplayedChild(SEARCH_LOADING_VIEW);
                break;
        }
    }

    @Override
    public void receiveResult(ATaskMark taskMark, ActionException exception, Object trackerResult) {
        if (exception == null) {

            if (mIsFirstRun) { // show search home
                mViewAnimator.setDisplayedChild(SEARCH_HOME_VIEW);
                HashMap searchInfo = imContext.getBusinessModule().getCacheManager().getSearchKeyWorkInfoMap();
                if (searchInfo != null) {
                    List<String> hotKeywordStrings = (List<String>) searchInfo.get(SearchInfoHandle.HOT_KEYWORDS);
                    mTrendingTagsAdapter.addItems(hotKeywordStrings);
                }

                mIsFirstRun = false;
            } else { // show search results after each subsequent search
                mViewAnimator.setDisplayedChild(SEARCH_RESULTS_VIEW);
                HashMap searchInfo = imContext.getBusinessModule().getCacheManager().getSearchKeyWorkInfoMap();
                if (searchInfo != null) {
                    int postTotalCount = (int) searchInfo.get(SearchInfoHandle.SEARCH_TOTALCOUNT_POST);
                    int businessTotalCount = (int) searchInfo.get(SearchInfoHandle.SEARCH_TOTALCOUNT_BUSINESS);
                    int eventTotalCount = (int) searchInfo.get(SearchInfoHandle.SEARCH_TOTALCOUNT_EVENT);
                    int userPostTotalCount = (int) searchInfo.get(SearchInfoHandle.SEARCH_TOTALCOUNT_USERPOST);

                    ((TextView) mPostSearchResult.findViewById(R.id.title)).setText(Html.fromHtml(getString(R.string.post_search_result_count, postTotalCount)));
                    ((TextView) mBusinessSearchResult.findViewById(R.id.title)).setText(Html.fromHtml(getString(R.string.business_search_result_count, businessTotalCount)));
                    ((TextView) mEventSearchResult.findViewById(R.id.title)).setText(Html.fromHtml(getString(R.string.event_search_result_count, eventTotalCount)));
                    ((TextView) mUserpostSearchResult.findViewById(R.id.title)).setText(Html.fromHtml(getString(R.string.userpost_search_result_count, userPostTotalCount)));

                    mPostSearchResult.setTag(postTotalCount);
                    mBusinessSearchResult.setTag(businessTotalCount);
                    mEventSearchResult.setTag(eventTotalCount);
                    mUserpostSearchResult.setTag(userPostTotalCount);
                }

            }
        }
    }

}
